// const baseUrl = require('../constant/constant')
import {
  baseUrl
} from '../constant/constant'
const requestData = (method, url, body) => {
  const cookie = wx.getStorageSync('cookie')
  let header = {}
  if (method == 'GET') {
    header['Content-Type'] = 'application/json'
  } else {
    header['Content-Type'] = 'application/x-www-form-urlencoded'
  }
  if (cookie) {
    header['cookie'] = cookie
    getApp().globalData.hasLogined = true
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method: method,
      header: header,
      data: body,
      success(response) {
        console.log('response', response)
        const res = response.data || {};
        if (res.errorCode != 0) {
          reject(res)
          if (res.errorMsg) {
            wx.showToast({
              title: res.errorMsg,
              icon: 'none'
            })
          }
        } else {
          if (url.indexOf('login') != -1) {
            wx.setStorageSync('cookie', response.header['Set-Cookie'])
          }
          if(url.indexOf('logout')!=-1){
            // wx.removeStorageSync('cookie')
            wx.clearStorageSync()
            getApp().globalData.hasLogined = false
          }
          resolve(res)
        }
      },
      fail(error) {
        reject(error)
        if (error.errorMsg) {
          if (error.errorMsg.indexOf('请先登录') != -1) {
            getApp().globalData.hasLogined = false
          }
          wx.showToast({
            title: error.errorMsg,
            icon: 'none'
          })
        }
      }
    })
  })
}
export const httpGet = (url, body) => {
  return requestData("GET", url, body)
}
export const httpPost = (url, body) => {
  return requestData("POST", url, body)
}
//  module.exports={
//    httpGet,httpPost
//  }